﻿using HCore;

namespace MEat
{
    public partial class MEatGame
    {
        private class ClientConnectState : State<MEatGame>
        {
            private bool _sendHello = false;

            public ClientConnectState(MEatGame owner) : base(owner)
            {
            }

            public override void Enter()
            {
                _owner.Log("Enter ConnectState");
                _owner.networkMgr.Register(PacketType.Hello, HelloHandle);
                _owner.networkMgr.Connect();
                _sendHello = false;
            }

            private void HelloHandle(InputMemoryBitStream input)
            {
                _owner._playerId = input.ReadInt();
                _owner.commandMgr.serverProxies.Add(_owner.playerId, _owner.playerName);
                int otherPlayerNum = input.ReadInt();
                for (int i = 0; i < otherPlayerNum; i++)
                {
                    int playerId = input.ReadInt();
                    string name = input.ReadString();
                    _owner.commandMgr.serverProxies.Add(playerId, name);
                }

                _owner.stateMachine.ChangeState<ClientLobbyState>();
            }

            public override void Execute()
            {
                if (!_owner.networkMgr.connected)
                {
                    return;
                }

                if (_sendHello)
                {
                    return;
                }

                OutputMemeryBitStream output = new OutputMemeryBitStream();
                output.WriteByte(PacketType.Hello);
                output.WriteString(_owner.playerName);
                _owner.networkMgr.Send(output.GetBuffer(), output.GetByteLength());
                _sendHello = true;
            }

            public override void Exit()
            {
                _owner.networkMgr.Unregister(PacketType.Hello);
                _owner.Log("Exit ConnectState");
            }
        }
    }
}